package com.cskaoyan.market.service.admin.impl;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.db.domain.MarketAdExample;
import com.cskaoyan.market.db.mapper.MarketAdMapper;
import com.cskaoyan.market.service.admin.MarketAdService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MarketAdServiceImpl implements MarketAdService {

    @Autowired
    MarketAdMapper adMapper;

    @Override
    public List<MarketAd> list(String page, String limit, String sort, String order, String name, String content) {
        //mybatis应该如何使用呢？\
        //获取加载当前类的类加载器，需要使用类加载器来帮助我们获取文件的路径、流
        //从工厂中获取一个sql会话

        //当我们执行当前对象的方法时，那么执行的便是对应的sql语句
        // 获取example
        MarketAdExample marketAdExample = new MarketAdExample();
        // 获取criteria
        MarketAdExample.Criteria criteria = marketAdExample.createCriteria();
        // 设置条件        
        // 排除已经被逻辑删除的
        criteria.andDeletedEqualTo(false);
        // 模糊查询
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(content)) {
            criteria.andContentEqualTo("%" + content + "%");
        }
        // 排序
        marketAdExample.orderBy(sort + " " + order);
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketAd> marketAds = adMapper.selectByExampleSelective(marketAdExample);

        return marketAds;
    }

    @Override
    public Integer create(MarketAd marketAd) {

        // 插入数据
        int resCode = adMapper.insertSelective(marketAd);

        return resCode;
    }

    @Override
    public int update(MarketAd marketAd) {

        //更新数据
        int resCode = adMapper.updateByPrimaryKeySelective(marketAd);

        return resCode;

    }

    @Override
    public int delete(MarketAd marketAd) {

        //删除数据
        int resCode = adMapper.logicalDeleteByPrimaryKey(marketAd.getId());

        return resCode;
    }

}
